package com.ruoyi.spspublic.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.PartyConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.spspublic.domain.*;
import com.ruoyi.spspublic.domain.constants.TicketConstants;
import com.ruoyi.spspublic.mapper.TMisSignMapper;
import com.ruoyi.spspublic.mapper.TMisTaskMapper;
import com.ruoyi.spspublic.service.ITMisSignService;
import com.ruoyi.spspublic.service.ITMisTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 签字信息Service业务层处理
 *
 * @author wangwei
 * @date 2021-06-23
 */
@Service
public class TMisSignServiceImpl implements ITMisSignService {
    @Autowired
    private TMisSignMapper tMisSignMapper;
/*    @Autowired
    private ITMisTaskService misTaskService;*/


    @Autowired
    private TMisTaskMapper tMisTaskMapper;

/*
    private static final Logger log = LoggerFactory.getLogger(com.ruoyi.party.spspublic.service.impl.TMisSignServiceImpl.class);
*/

    /**
     * 查询签字信息
     *
     * @param ctId 签字信息ID
     * @return 签字信息
     */
    @Override
    public TMisSign selectTMisSignById(String ctId) {
        return tMisSignMapper.selectTMisSignById(ctId);
    }

    /**
     * 查询签字信息列表
     *
     * @param tMisSign 签字信息
     * @return 签字信息
     */
    @Override
    public List<TMisSign> selectTMisSignList(TMisSign tMisSign) {
        return tMisSignMapper.selectTMisSignList(tMisSign);
    }

    /**
     * 新增签字信息
     *
     * @param tMisSign 签字信息
     * @return 结果
     */
    @Override
    public int insertTMisSign(TMisSign tMisSign) {
        return tMisSignMapper.insertTMisSign(tMisSign);
    }

    /**
     * 修改签字信息
     *
     * @param tMisSign 签字信息
     * @return 结果
     */
    @Override
    public int updateTMisSign(TMisSign tMisSign) {
        return tMisSignMapper.updateTMisSign(tMisSign);
    }

    /**
     * 批量删除签字信息
     *
     * @param ctIds 需要删除的签字信息ID
     * @return 结果
     */
    @Override
    public int deleteTMisSignByIds(String[] ctIds) {
        return tMisSignMapper.deleteTMisSignByIds(ctIds);
    }

    /**
     * 删除签字信息信息
     *
     * @param ctId 签字信息ID
     * @return 结果
     */
    @Override
    public int deleteTMisSignById(String ctId) {
        return tMisSignMapper.deleteTMisSignById(ctId);
    }

    @Override
    public int selectExistSigns(String functionNo, String businessNo) {
        return tMisSignMapper.selectExistSigns(functionNo, businessNo);
    }

    @Override
    public void updateExpiredSign(TMisSign querySign) {
        tMisSignMapper.updateExpiredSign(querySign);
    }

    @Override
    public TMisSign createSignByTask(TMisTask task) {
        return null;
    }

    /**
     * 批量签发审批
     *
     * @param batchSignDto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult batchSign(BatchSignDto batchSignDto) {
      /*  // 查询function信息
        TMisFunction tMisFunction =
                itMisFunctionService.selectTMisFunctionById(batchSignDto.getFunNo());
        if (StringUtils.isNull(tMisFunction)) {
            throw new BaseException("无法搜索到对应的功能号，请联系管理员");
        }
        // 当前登录用户
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        // 验证单据数据的有效性
        String ctTable = tMisFunction.getCtTable();
        if (StringUtils.isEmpty(ctTable)) {
            throw new BaseException("未查询到对应的表数据，请联系管理员");
        }
        for (String ctId : batchSignDto.getCtIdList()) {
            BatchSignSearchDto forSearch = new BatchSignSearchDto();
            forSearch.setTableName(ctTable);
            forSearch.setCtId(ctId);
            SingleSignData singleSignData = tMisSignMapper.selectByCtId(forSearch);
            singleSignData.setTableName(ctTable);
            if (StringUtils.isNull(singleSignData)) {
                log.error("batchSign selectById: " + ctId + "未查到数据");
                throw new BaseException("无法查询到对应的审批数据，请联系管理员");
            }
            // 权限判断
            if (!loginUser.getManagementOrgLevel().equals(singleSignData.getCtCurStepNo())) {
                log.error("当前组织" + loginUser.getManagementOrgName() + "没有签发权限");
                throw new BaseException("当前组织" + loginUser.getManagementOrgName() + "没有签发权限");
            }
            List<String> stepList = Arrays.asList(singleSignData.getCtHisStepNo().split(","));
            if (PartyConstants.SIGN_AGREE.equals(batchSignDto.getType())) {
                // 同意
                if (stepList.isEmpty()) {
                    log.error("batchSign ctId: " + ctId + "getCtHisStepNo 未查到数据");
                    throw new BaseException("无法查询到对应的审批数据，请联系管理员");
                }
                if (!stepList.contains(singleSignData.getCtCurStepNo())) {
                    log.error("batchSign ctId: " + ctId + "getCtCurStepNo 无法匹配到HisStepNo中的数据");
                    throw new BaseException("无法查询到对应的审批数据，请联系管理员");
                }
                // 当前步骤位置索引
                int currentStepIndex = stepList.indexOf(singleSignData.getCtCurStepNo());
                if (++currentStepIndex < stepList.size() && currentStepIndex != -1) {
                    singleSignData.setCtCurStepNo(stepList.get(currentStepIndex));
                } else {
                    singleSignData.setCtCurStepNo(PartyConstants.SIGN_END);
                }
                singleSignData.setCtEnd(Constants.ONE);
            } else {
                // 不同意
                // 判断一个","字符串是否存在   因为存在集团党委录入的情况，集团录入时候没有流程
                boolean status = singleSignData.getCtHisStepNo().contains(",");
                if (status) {
                    String firstStep =
                            singleSignData
                                    .getCtHisStepNo()
                                    .substring(singleSignData.getCtHisStepNo().indexOf(","));
                    if (loginUser.getManagementOrgLevel().equals(firstStep)) {
                        throw new CustomException("当前单据状态不能退回!");
                    }
                    singleSignData.setCtEnd(Constants.ZERO);
                    singleSignData.setCtCurStepNo(stepList.get(0));
                } else {
                    throw new CustomException("当前单据状态不能退回!");
                }
            }
            tMisSignMapper.updateSignData(singleSignData);
            // 添加任务信息
            insertTask(singleSignData, batchSignDto, loginUser);

            // 组织考评审批特例处理
            // todo 20221103 注销
            // specialCase(singleSignData, batchSignDto);
        }*/
        return AjaxResult.success("审批完成");
    }

    /**
     * 添加待办任务数据
     *
     * @param batchSignDto
     */
    private void insertTask(){
          /*  SingleSignData singleSignData, BatchSignDto batchSignDto, SysUser loginUser) {
        try {
            TMisSign tMisSign = new TMisSign();
            //BaseEntityUtils.createBaseDomain(tMisSign);
            tMisSign.setCtBussId(singleSignData.getCtId());
            tMisSign.setCtFunNo(batchSignDto.getFunNo());
*//*
            tMisSign.setCtFlowNo(loginUser.getManagementOrgLevel());
*//*
            tMisSign.setCtComment(batchSignDto.getReason());
            int existSign = selectExistSigns(batchSignDto.getFunNo(), singleSignData.getCtId());
            tMisSign.setCtStepNo(++existSign);
            tMisSign.setCtSign(TicketConstants.TICKET_IN_PROGRESS);
            String ctCurStepNo = singleSignData.getCtCurStepNo();
            tMisSign.setCtInceptCode(ctCurStepNo);
            if (PartyConstants.SIGN_END.equals(ctCurStepNo)) {
                tMisSign.setCtInceptName("结束");
            } else {
              //PublicTDwBranch branchName = branchMapper.selectBranchByCodeP2(ctCurStepNo);
              PublicTDwBranch branchName = new PublicTDwBranch();
                tMisSign.setCtInceptName(branchName.getCtBranchAbbreviation());
            }
            tMisSign.setDtDate(DateUtils.getNowDate());
            tMisSign.setCtUsercode(loginUser.getUserName());
            tMisSign.setCtUsername(loginUser.getNickName());

            insertTMisSign(tMisSign);

            TMisFunction tMisFunction =
                    misFunctionService.selectTMisFunctionById(batchSignDto.getFunNo());

            String time2 = DateUtils.getTime();
            TMisTask oldTask =
                    misTaskService.selectOldTask(batchSignDto.getFunNo(), singleSignData.getCtId());
            PublicTDwBranch branch = branchMapper.selectTDwBranchById(singleSignData.getCtBranch());
            if (oldTask != null) {
                if (PartyConstants.SIGN_AGREE.equals(batchSignDto.getType())) {
                    if ("E".equals(singleSignData.getCtCurStepNo())) {
                        oldTask.setCtFinish(TicketConstants.FINISHED);
                        oldTask.setCtName(
                                branch.getCtBranchAbbreviation()
                                        + "提交的"
                                        + singleSignData.getCtName()
                                        + "于"
                                        + time2
                                        + "被"
                                        + loginUser.getManagementOrgName()
                                        + "审批，审批结束！");
                    }
                    oldTask.setCtName(loginUser.getManagementOrgName() + "于" + time2 + "提交申请，请您审批！");
                    oldTask.setCtInceptP(singleSignData.getCtCurStepNo());
                    oldTask.setDtDateEnd(DateUtils.getNowDate());
                } else {
                    oldTask.setCtInceptP(branch.getCtCodeP2());
                    oldTask.setCtName(
                            branch.getCtBranchAbbreviation()
                                    + "提交的"
                                    + singleSignData.getCtName()
                                    + "申请于"
                                    + time2
                                    + "已被 "
                                    + loginUser.getManagementOrgName()
                                    + " 退回，退回原因是："
                                    + batchSignDto.getReason());
                }
                misTaskService.updateTMisTask(oldTask);
            } else {
                // 新建任务
                TMisTask task = new TMisTask();
                BaseEntityUtils.createBaseDomain(task);
                task.setCtFunNo(batchSignDto.getFunNo());
                task.setCtInceptType("b");
                task.setCtInceptP(singleSignData.getCtCurStepNo());
                task.setCtBussId(singleSignData.getCtId());
                task.setDtDateSend(DateUtils.getNowDate());
                task.setCtType(tMisFunction.getCtFunName());
                task.setCtSendP(loginUser.getUserName());
                task.setCtName(
                        branch.getCtBranchAbbreviation()
                                + "于"
                                + time2
                                + "提交的"
                                + singleSignData.getCtName()
                                + "申请，请您审批！");
                task.setCtFinish(TicketConstants.TICKET_IN_PROGRESS);
                task.setCtBranch(loginUser.getManagementOrg());
                misTaskService.insertTMisTask(task);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }*/
    }

    /**
     * 组织考评审批特例处理
     */
    private void specialCase(SingleSignData singleSignData, BatchSignDto batchSignDto) {

    }
}
